import WxValidate from "../../utils/WxValidate.js";
import { VerificationCode,sign } from "../../api/user.js";
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import store from '../../Store/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    value:'',
    type:true,
    time:'59',
    form:{
      mobile:'',
      code:''
    }
  },
// 验证码输入
verification(e){
this.setData({
  "form.code": e.detail
})
},

// 手机号输入
   updateValue(e){
   this.setData({
   "form.mobile":e.detail
})
  },
// 验证码点击
 async clickNumber(){
 try{
  const res= await VerificationCode(this.data.form.mobile)
  wx.showToast({
    title:'验证码已发送',
    icon:'success',
  })
  console.log(res);
   this.setData({
    type:false
   })
   let times= setInterval(() => {
    this.setData({
      time:this.data.time-1
    })
    if(this.data.time===0){
      clearInterval(times)
      this.setData({
        type:true,
        time:59
      })
    } 
   }, 1000);
 } catch(err){
wx.showToast({
title:'验证码发送失败',
icon:'error'
})
 }

  

  },

  // 校验规则

  initValidate(){
const rules={
  mobile:{
    required: true,
    minlength: 1
  },
  code:{
    required: true,
    minlength: 1
  }
}
const messages={
  mobile:{
    required: '请填写姓名',
    minlength: '请输入正确的名称'

  },
  code:{
    required: '请填写姓名',
    minlength: '请输入正确的名称'

  },
 
}
this.WxValidate = new WxValidate(rules, messages)
console.log(this.WxValidate)

  },
  
// 提交判断
 formSubmit:async function (e) {
    const params = e.detail.value
    //校验表单
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      wx.showToast({
        title: '未填写必填项',
        icon: 'none'
      })
      return false
    }
    // 点击登录
    try{
      const res= await sign(this.data.form)
      wx.setStorageSync('refresh_token', res.data.refresh_token);
      wx.setStorageSync('token', res.data.token); 
      this.setToken(res.data.token)
      console.log(res);
       wx.redirectTo({
      url: `/pages/my/my?mobile=${this.data.form.mobile}`})
    } catch(err){
      wx.showToast({
        title:'验证码错误',
        icon:'error'
        })
    }
    return true;

    

  



  },
  
  
  


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
   this.initValidate()
   createStoreBindings(this, {
    store: store,
    fields: ['token'],
    actions: ['setToken']
  })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})